<template>
  <div class="constraint-config-panel">
    <!-- 约束配置标题区域 -->
    <div class="panel-header" v-if="constraintConfigData">
      <div class="panel-title-section">
        <span class="panel-title">
          <el-icon style="margin-right: 8px;"><Setting /></el-icon>
          {{ constraintConfigData.title }}
        </span>
        <el-tag 
          v-if="isNewConstraint" 
          type="success" 
          size="small"
          style="margin-left: 10px;"
        >
          新建
        </el-tag>
      </div>
      <div class="config-actions">
        <el-button 
          type="primary" 
          size="small"
          @click="validateAllConfig"
        >
          验证配置
        </el-button>
        <el-button 
          type="success" 
          size="small"
          @click="saveAllConfig"
        >
          保存配置
        </el-button>
      </div>
    </div>
    
    <!-- 新约束提示 -->
    <el-alert
      v-if="constraintConfigData && isNewConstraint"
      title="新约束配置"
      type="info"
      description="这是一个新创建的约束配置，请设置相关参数后保存。"
      style="margin-bottom: 15px;"
      show-icon
      :closable="false"
    />
    
    <el-divider class="custom-divider" v-if="constraintConfigData" />

    <!-- APS参数设定区域 -->
    <div v-if="constraintConfigData" class="config-content">
      <!-- 基础参数设定 -->
      <BaseParametersConfig 
        ref="baseParamsRef" 
        v-model="baseParamsData" 
        :collapsed="baseParamsCollapsed"
        @update:collapsed="baseParamsCollapsed = $event" 
        @data-change="handleDataChange"
        @validation-change="handleValidationChange"
      />

      <!-- 上班时段初始化 -->
      <WorkTimeConfig 
        ref="workTimeRef" 
        v-model="workTimeData" 
        :collapsed="workTimeCollapsed"
        @update:collapsed="workTimeCollapsed = $event" 
        @data-change="handleDataChange"
        @validation-change="handleValidationChange"
      />

      <!-- 设备选用 -->
      <DeviceConfig 
        ref="deviceRef" 
        v-model="deviceData" 
        :collapsed="deviceCollapsed"
        :selected-orders="selectedOrders"
        @update:collapsed="deviceCollapsed = $event" 
        @data-change="handleDataChange"
        @validation-change="handleValidationChange"
      />
    </div>

    <!-- 空状态提示 -->
    <div v-if="!constraintConfigData" class="empty-state">
      <div class="empty-content">
        <el-icon size="48" color="#c0c4cc">
          <Setting />
        </el-icon>
        <p>请在左侧选择约束配置</p>
        <p class="empty-desc">选择约束配置后，可以在此处进行参数设定</p>
      </div>
    </div>

    <!-- 加载状态
    <div v-if="loading" class="loading-overlay">
      <el-loading-service />
    </div> -->
  </div>
</template>

<script>
import { ref, watch, computed, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting } from '@element-plus/icons-vue'
import BaseParametersConfig from '@/components/visualiszation/BaseParametersConfig.vue'
import WorkTimeConfig from '@/components/visualiszation/WorkTimeConfig.vue'
import DeviceConfig from '@/components/visualiszation/DeviceConfig.vue'
import { constraintApi } from '@/api/constraint'
import {
  baseParamsInitialData,
  workTimeInitialData,
  deviceInitialData,
  createInitialConfigData,
  ErrorMessages,
  SuccessMessages
} from '../../views/VisualizationConfig'

export default {
  name: 'ConstraintConfigPanel',
  components: {
    BaseParametersConfig,
    WorkTimeConfig,
    DeviceConfig,
    Setting
  },
  props: {
    // 当前选中的约束配置索引
    selectedConstraintIndex: {
      type: Number,
      default: null
    },
    // 约束配置ID
    constraintConfigId: {
      type: String,
      default: null
    },
    // 约束配置名称（由父组件传递，严格使用父组件的值）
    constraintConfigTitle: {
      type: String,
      default: null
    },
    // 是否为新创建的约束（由父组件判断并传递）
    isNewConstraint: {
      type: Boolean,
      default: false
    },
    // 已选择的工单数据（传给设备配置）
    selectedOrders: {
      type: Array,
      default: () => []
    },
    // 是否显示加载状态
    loading: {
      type: Boolean,
      default: false
    }
  },
  emits: [
    'constraint-loaded', 
    'constraint-load-failed',
    'constraint-status-checked',
    'config-changed',
    'config-validated',
    'config-saved'
  ],
  setup(props, { emit }) {

    // ============== 数据定义 ==============
    const constraintConfigData = ref(null)
    
    /**
     * 初始化所有默认数据
     */
    const initializeAllDefaultData = (constraintInfo = null) => {
      // 创建完整的默认配置数据
      const defaultConfig = createInitialConfigData()
      
      // 如果有约束信息，则设置到基础参数中
      if (constraintInfo) {
        defaultConfig.baseParameters.constraintInfo = constraintInfo
      }
      
      return defaultConfig
    }
    
    // 使用默认数据初始化
    const initialConfig = initializeAllDefaultData()
    const baseParamsData = ref({ ...initialConfig.baseParameters })
    const workTimeData = ref([...initialConfig.workTimeConfiguration])
    const deviceData = ref([...initialConfig.deviceConfiguration])
    
    // 组件折叠状态
    const baseParamsCollapsed = ref(false)
    const workTimeCollapsed = ref(false)
    const deviceCollapsed = ref(false)

    // 组件引用
    const baseParamsRef = ref(null)
    const workTimeRef = ref(null)
    const deviceRef = ref(null)

    // 验证状态
    const validationErrors = ref({
      baseParams: [],
      workTime: [],
      device: []
    })

    // ============== 计算属性 ==============
    const isConfigValid = computed(() => {
      const allErrors = [
        ...validationErrors.value.baseParams,
        ...validationErrors.value.workTime,
        ...validationErrors.value.device
      ]
      return allErrors.length === 0
    })

    const hasConfigData = computed(() => {
      return constraintConfigData.value !== null
    })

    // ============== 方法定义 ==============

    /**
     * 加载约束配置详情
     */
    const loadConstraintConfig = async (constraintId) => {
      if (!constraintId) {
        constraintConfigData.value = null
        resetFormData()
        return
      }

      // ✨ 立即初始化默认数据，确保界面切换时就有完整配置
      const constraintInfo = {
        id: constraintId,
        title: props.constraintConfigTitle || '新约束配置'
      }
      
      const defaultConfig = initializeAllDefaultData(constraintInfo)
      
      // 立即应用默认数据到界面
      baseParamsData.value = { ...defaultConfig.baseParameters }
      workTimeData.value = [...defaultConfig.workTimeConfiguration]
      deviceData.value = [...defaultConfig.deviceConfiguration]
      
      // 设置约束配置基本信息
      constraintConfigData.value = {
        id: constraintId,
        title: props.constraintConfigTitle || '新约束配置'
      }

      try {
        const res = await constraintApi.getById(constraintId)
        const schedulingPlanGenerateDto = res?.data || {}
        
        // 检查是否有配置数据 - 当返回空或无配置数据时视为新建状态
        const hasConfigData = !!(schedulingPlanGenerateDto.baseParameters || 
                                 schedulingPlanGenerateDto.workTimeConfiguration || 
                                 schedulingPlanGenerateDto.deviceConfiguration)
        const isNewConstraint = !hasConfigData || Object.keys(schedulingPlanGenerateDto).length === 0
        
        // 通知父组件约束的状态检查结果
        emit('constraint-status-checked', {
          constraintId,
          isNewConstraint,
          hasConfigData
        })
        
        // 🔄 如果后端有数据，则使用后端数据覆盖默认数据
        if (hasConfigData) {
          if (schedulingPlanGenerateDto.baseParameters) {
            loadBaseParametersData(schedulingPlanGenerateDto.baseParameters)
          }
          
          if (schedulingPlanGenerateDto.workTimeConfiguration) {
            loadWorkTimeData(schedulingPlanGenerateDto.workTimeConfiguration)
          }
          
          if (schedulingPlanGenerateDto.deviceConfiguration) {
            loadDeviceData(schedulingPlanGenerateDto.deviceConfiguration)
          }
          // 默认数据已经在前面应用了，这里不需要再做任何操作
        }
        
        
        emit('constraint-loaded', {
          config: constraintConfigData.value,
          fullData: schedulingPlanGenerateDto
        })
      } catch (e) {
        // 接口失败时，保持已应用的默认数据
        if (e?.response?.status !== 404 && e?.response?.status !== 204) {
          ElMessage.error('加载约束配置失败，使用默认配置')
        }
        
        // 通知父组件这是新约束
        emit('constraint-status-checked', {
          constraintId,
          isNewConstraint: true,
          hasConfigData: false
        })
        
        ElMessage.success('约束配置已准备就绪（使用默认配置），请开始设置参数')
        
        emit('constraint-loaded', {
          config: constraintConfigData.value,
          fullData: {}
        })
      }
    }

    /**
     * 重置表单数据为默认值
     */
    const resetFormData = () => {
      console.log('🔄 重置表单数据为默认值')
      
      // 使用统一的初始化函数重置数据
      const defaultConfig = initializeAllDefaultData()
      baseParamsData.value = { ...defaultConfig.baseParameters }
      workTimeData.value = [...defaultConfig.workTimeConfiguration]
      deviceData.value = [...defaultConfig.deviceConfiguration]
      
      // 重置验证状态
      validationErrors.value = {
        baseParams: [],
        workTime: [],
        device: []
      }
    }

    /**
     * 加载基础参数设定数据
     */
    const loadBaseParametersData = (data) => {
      baseParamsData.value = { ...baseParamsData.value, ...data }
      if (baseParamsRef.value) {
        nextTick(() => {
          baseParamsRef.value.loadData(data)
        })
      }
    }

    /**
     * 加载工作时间配置数据
     */
    const loadWorkTimeData = (data) => {
      workTimeData.value = data || [...workTimeInitialData]
      if (workTimeRef.value) {
        nextTick(() => {
          workTimeRef.value.loadData(data)
        })
      }
    }

    /**
     * 加载设备配置数据
     */
    const loadDeviceData = (data) => {
      deviceData.value = data || [...deviceInitialData]
      if (deviceRef.value) {
        nextTick(() => {
          deviceRef.value.loadData(data)
        })
      }
    }

    /**
     * 处理数据变化，发送更新请求
     */
    const handleDataChange = async (componentType, newData) => {
      if (!constraintConfigData.value?.id) {
        console.log('⚠️ 没有选中的约束配置，跳过数据更新')
        return
      }

      console.log(`🔄 ${componentType} 数据发生变化，准备更新到后端:`, newData)

      try {
        // TODO: 调用后端更新接口
        const updateData = {
          constraintId: constraintConfigData.value.id,
          componentType,
          data: newData,
          timestamp: new Date().toISOString()
        }
        
        console.log('📡 TODO: 调用后端更新接口，数据:', updateData)
        
        // 这里应该调用实际的API
        // await constraintApi.updateConfig(updateData)
        
        emit('config-changed', {
          type: componentType,
          data: newData,
          constraintId: constraintConfigData.value.id
        })
        
        // 暂时只做日志记录
        // ElMessage.success('配置更新成功')
      } catch (error) {
        ElMessage.error('配置更新失败')
      }
    }

    /**
     * 处理验证状态变化
     */
    const handleValidationChange = (componentType, errors) => {
      validationErrors.value[componentType] = errors
    }

    /**
     * 验证所有配置
     */
    const validateAllConfig = async () => {
      if (!constraintConfigData.value) {
        ElMessage.warning('请先选择约束配置')
        return false
      }

      const errors = []

      try {
        // 验证基础参数
        if (baseParamsRef.value) {
          const baseValidation = await baseParamsRef.value.validateForm()
          if (!baseValidation.valid) {
            errors.push(...baseValidation.errors.map(err => `基础参数: ${err}`))
          }
        }

        // 验证工作时间配置
        if (workTimeRef.value) {
          const workTimeValidation = workTimeRef.value.validateForm()
          if (!workTimeValidation.valid) {
            errors.push(...workTimeValidation.errors.map(err => `工作时间: ${err}`))
          }
        }

        // 验证设备配置
        if (deviceRef.value) {
          const deviceValidation = deviceRef.value.validateForm()
          if (!deviceValidation.valid) {
            errors.push(...deviceValidation.errors.map(err => `设备配置: ${err}`))
          }
        }

        const isValid = errors.length === 0

        emit('config-validated', {
          isValid,
          errors,
          constraintId: constraintConfigData.value.id
        })

        if (!isValid) {
          ElMessage.warning(`发现 ${errors.length} 个配置问题`)
        }

        return isValid
      } catch (error) {
        ElMessage.error('配置验证失败')
        return false
      }
    }

    /**
     * 保存所有配置
     */
    const saveAllConfig = async () => {
      if (!constraintConfigData.value) {
        ElMessage.warning('请先选择约束配置')
        return
      }

      // 先验证配置
      const isValid = await validateAllConfig()
      if (!isValid) {
        ElMessage.error('请先修复配置问题再保存')
        return
      }

      try {
        // 构建SchedulingPlanGenerateDto数据格式
        const baseParameters = baseParamsRef.value?.getFormData() || baseParamsData.value
        const workTimeConfiguration = workTimeRef.value?.getFormData() || workTimeData.value
        const deviceConfiguration = deviceRef.value?.getFormData() || deviceData.value

        // 确保baseParameters中包含正确的约束信息，使用后端要求的属性名 id 和 title
        const schedulingPlanGenerateDto = {
          baseParameters: {
            ...baseParameters,
            constraintInfo: {
              id: props.constraintConfigId,  // 严格使用父组件传递的约束配置id
              title: props.constraintConfigTitle,  // 严格使用父组件传递的约束名称
              ...baseParameters.constraintInfo  // 保留其他原有属性
            }
          },
          workTimeConfiguration,
          deviceConfiguration
        }
        
        console.log('💾 保存约束配置:', {
          constraintId: props.constraintConfigId,
          constraintTitle: props.constraintConfigTitle,
          baseParamsCount: Object.keys(baseParameters).length,
          workTimeCount: workTimeConfiguration.length,
          deviceCount: deviceConfiguration.length,
          timestamp: new Date().toISOString()
        })

        // 调用后端保存接口
        const response = await constraintApi.save(schedulingPlanGenerateDto)
        
        // 保存成功后，更新新建状态为false（不再是新建状态）
        emit('constraint-status-checked', {
          constraintId: constraintConfigData.value.id,
          isNewConstraint: false,
          hasConfigData: true
        })
        
        emit('config-saved', {
          constraintId: constraintConfigData.value.id,
          configData: schedulingPlanGenerateDto,
          success: true,
          response
        })

      } catch (error) {
        ElMessage.error('配置保存失败: ' + (error.message || '未知错误'))
        
        emit('config-saved', {
          constraintId: constraintConfigData.value?.id,
          success: false,
          error
        })
      }
    }

    // ============== 监听器 ==============

    // 监听约束配置ID变化
    watch(
      () => props.constraintConfigId,
      (newId, oldId) => {
        loadConstraintConfig(newId)
      },
      { immediate: true }
    )

    // 监听约束配置名称变化，更新显示的标题
    watch(
      () => props.constraintConfigTitle,
      (newTitle, oldTitle) => {
        if (constraintConfigData.value && newTitle) {
          constraintConfigData.value.title = newTitle
        }
      }
    )

    // 监听选中的工单变化
    watch(
      () => props.selectedOrders,
      (newOrders, oldOrders) => {
      },
      { deep: true }
    )

    // ============== 返回 ==============
    return {
      // 数据
      constraintConfigData,
      baseParamsData,
      workTimeData,
      deviceData,
      baseParamsCollapsed,
      workTimeCollapsed,
      deviceCollapsed,
      validationErrors,

      // 计算属性
      isConfigValid,
      hasConfigData,

      // 引用
      baseParamsRef,
      workTimeRef,
      deviceRef,

      // 方法
      handleDataChange,
      handleValidationChange,
      validateAllConfig,
      saveAllConfig,
      loadConstraintConfig,
      resetFormData,
      initializeAllDefaultData
    }
  }
}
</script>

<style scoped>
.constraint-config-panel {
  height: 100%;
  position: relative;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  padding: 15px 0;
}

.panel-title-section {
  display: flex;
  align-items: center;
}

.panel-title {
  font-weight: 700;
  font-size: 24px;
  color: #714B67;
  font-family: "Microsoft YaHei", "Noto Sans SC", sans-serif;
  display: flex;
  align-items: center;
}

.config-actions {
  display: flex;
  gap: 10px;
}

.config-content {
  padding: 0;
}

.custom-divider {
  margin: 20px 0;
  border-style: dotted;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
  color: #909399;
}

.empty-content {
  text-align: center;
}

.empty-content p {
  margin-top: 16px;
  font-size: 14px;
}

.empty-desc {
  color: #C0C4CC;
  font-size: 12px;
  margin-top: 8px;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}
</style>
